﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace EventLesson
{
    /// <summary>
    /// BehaviorWindow.xaml 的交互逻辑
    /// </summary>
    public partial class BehaviorWindow : Window
    {
        public BehaviorWindow()
        {
            InitializeComponent();
        }
    }

    // 创建一个行为类，用来封装事件逻辑：对象移动的事件 
    public class DragMoveBehavior : Behavior<FrameworkElement>
    {
        // 执行当前行为所依附的对象的事件挂载
        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
            AssociatedObject.MouseMove += AssociatedObject_MouseMove;
            AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp;
        }
        protected override void OnDetaching()
        {
            base.OnDetaching();

            AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown;
            AssociatedObject.MouseMove -= AssociatedObject_MouseMove;
            AssociatedObject.MouseLeftButtonUp -= AssociatedObject_MouseLeftButtonUp;
        }

        private void AssociatedObject_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            is_obj_moving = false;

            Mouse.Capture(null);
        }

        private void AssociatedObject_MouseMove(object sender, MouseEventArgs e)
        {
            if (is_obj_moving == false) return;

            //光标移动后，在Canvas上的当前位置


            Point p = e.GetPosition(AssociatedObject.Parent as Canvas);

            double offset_x = p.X - start_point.X;   // 偏移100
            double offset_y = p.Y - start_point.Y;   // 偏移50


            Canvas.SetLeft((UIElement)sender, start_x + offset_x);
            Canvas.SetTop((UIElement)sender, start_y + offset_y);
        }

        private void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // 获取光标在Canvas上的当前位置
            start_point = e.GetPosition(AssociatedObject.Parent as Canvas);

            start_x = Canvas.GetLeft((UIElement)sender);// 当前50
            //或者 var x = (sender as UIElement).GetValue(Canvas.LeftProperty);
            start_y = Canvas.GetTop((UIElement)sender); // 当前50

            is_obj_moving = true;

            // 把对象绑定到光标上   两种处理
            // 1、
            Mouse.Capture((UIElement)sender);
        }
        private Point start_point;
        private double start_x, start_y;
        private bool is_obj_moving = false;
    }
}
